package com.sdemo.modules.sys.controller;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.sdemo.common.globals.Globals;
import com.sdemo.modules.sys.model.Menu;
import com.sdemo.modules.sys.model.User;
import com.sdemo.modules.sys.service.UserService;
import com.sdemo.modules.sys.service.impl.RoleServiceImpl;
import com.sdemo.utils.MD5;
import com.sdemo.utils.Ret;
import com.sdemo.utils.ShiroUtils;
import com.sdemo.utils.VerifyCodeUtils;
import com.sdemo.utils.vcode.Captcha;
import com.sdemo.utils.vcode.GifCaptcha;

@Controller
@RequestMapping("/sys")
public class LoginController {
	
	private static final Logger logger = LoggerFactory.getLogger(LoginController.class);

	@Autowired
	 private Globals globals;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private RoleServiceImpl roleServiceImpl; 
	
	@RequestMapping("/login")
	@ResponseBody
	public Ret login(HttpServletRequest req,User user,String code){
		logger.info("globals kye:{}",globals.getKey());
		User users = null;
		
		//对比验证码
		String producercode = (String)ShiroUtils.getSessionAttribute(Globals.VERIFYCODE);
		logger.info("login从ShrioSession取出 verifyCode:"+producercode);
		
		if(!code.equals(producercode)){
			return Ret.error("验证码错误");
		}
		
		
		
		
		
		String password =MD5.getMD5(user.getPassword());
 
		try {
			users = userService.queryUser(user);
 
			if(password.equals(users.getPassword())){
				 UsernamePasswordToken token = new UsernamePasswordToken(user.getUsername(), password);
			        try{
			            Subject subject = SecurityUtils.getSubject();
			            subject.login(token);
			            List<Menu> list = roleServiceImpl.queryAuthByRoleid(users.getUserId());
			            Set<String> set = new HashSet<>();
			            for(int i = 0 ; i < list.size(); i++){
			            	 set.add(list.get(i).getAuthvalue());
			            }
			            return Ret.ok("认证成功").put("username", users.getUsername()).put("auth", set); 
			        } catch (Exception e) {
			        	 token.clear();
			        }
			}
			return Ret.error("用户或密码错误!!");
		} catch (Exception e) {
			logger.error("login error",e);
			return Ret.error("出错了");
		}		
	}
	
	@RequestMapping("/logout")
	@ResponseBody
	public Ret logout(HttpServletRequest request,HttpServletResponse response){
		try{
			request.getSession().invalidate();
		} catch (Exception e) {
			logger.error("login error",e);
		}		
		return Ret.ok();
	}
	/*
	//获取验证码(静态jpg版)
	@RequestMapping(value="/getYzm",method=RequestMethod.GET)
	public void getYzm(HttpServletResponse response,HttpServletRequest request){
		try {
			response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "no-cache");  
	        response.setDateHeader("Expires", 0);  
	        response.setContentType("image/jpeg");  
	          
	        //生成随机字串  
	        String verifyCode = VerifyCodeUtils.generateVerifyCode(4);  
	        //存入会话session  
	        HttpSession session = request.getSession(true);  
	        session.setAttribute("_code", verifyCode.toLowerCase());  
	        //生成图片  
	        int w = 146, h = 33;  
	        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
		} catch (Exception e) {
			logger.error("获取验证码异常：%s",e.getMessage());
		}
	}
	*/
	
	/**
	 * 获取验证码（jpg版本）
	 * @param response
	 */
	@RequestMapping(value="/getYzm",method=RequestMethod.GET)
	public void getYzm(HttpServletResponse response,HttpServletRequest request){
		try {
			response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "no-cache");  
	        response.setDateHeader("Expires", 0);  
	        response.setContentType("image/jpeg");  
	          
	        //生成随机字串  
	        String verifyCode = VerifyCodeUtils.generateVerifyCode(4); 
	        logger.info("getYzm verifyCode:"+verifyCode);
	     
	        //保存到shiro session
			ShiroUtils.setSessionAttribute(Globals.VERIFYCODE, verifyCode);
	        //生成图片  
	        int w = 146, h = 33;  
	        VerifyCodeUtils.outputImage(w, h, response.getOutputStream(), verifyCode);  
		} catch (Exception e) {
			logger.error("获取验证码异常：%s",e.getMessage());
		}
	}
	
	
	
	/**
	 * 获取验证码（Gif版本）
	 * @param response
	 */
	@RequestMapping(value="/getGifCode",method=RequestMethod.GET)
	public void getGifCode(HttpServletResponse response,HttpServletRequest request){
		try {
			response.setHeader("Pragma", "No-cache");  
	        response.setHeader("Cache-Control", "no-cache");  
	        response.setDateHeader("Expires", 0);  
	        response.setContentType("image/gif");  
	        /**
	         * gif格式动画验证码
	         * 宽，高，位数。
	         */
	        Captcha captcha = new GifCaptcha(146,33,4);
	        //获取随机字符串
	        String getText = new String(captcha.getChar());
	        
	        //存入Session
	        //方式一: HttpSession
	        //HttpSession session = request.getSession(true); 
	        //session.setAttribute("_code",captcha.text().toLowerCase());  
	        
	        //方式二: shiro session
			ShiroUtils.setSessionAttribute(Globals.VERIFYCODE, getText);
			System.out.println("ShiroSession保存-Code========================="+getText);
	        //输出
	        captcha.out(response.getOutputStream());
	        //不区分大小写:
	        //System.out.println("前端显示-Code============================"+captcha.text().toLowerCase());
	        
	        //区分大小写:
	        System.out.println("前端显示-Code============================"+captcha.text());
		} catch (Exception e) {
			logger.error( "获取验证码异常：%s",e.getMessage());
		}
	}
}
